package com.wits.qso.web.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.web.Servlets;

import com.wits.platform.common.constants.ViewType;
import com.wits.platform.common.constants.WebConstants;
import com.wits.platform.common.utils.PageUtil;
import com.wits.platform.common.utils.StringUtil;
import com.wits.platform.web.controller.BaseController;
import com.wits.platform.web.mvc.PageParam;
import com.wits.qso.entity.Year;
import com.wits.qso.service.YearService;

@Controller
@RequestMapping(value = "qso/year")
public class YearController extends BaseController
{

	/**
	 * 注入yearService
	 */
	@Autowired
	private YearService yearService;

	@RequestMapping(value = "/toList")
	public String toList() {
		return "qso/year/list";
	}

	/**
	 * 加载学年列表信息
	 * 
	 * @param model
	 * @param page
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/list")
	@ResponseBody
	public String list(Model model, @ModelAttribute("page") PageParam page, HttpServletRequest req) {
		Map<String, Object> searchParams = Servlets.getParametersStartingWith( req, "search_" );
		Page<Year> listPage = yearService.findPage( Year.class, searchParams, page );
		model.addAttribute( "searchParams", Servlets.encodeParameterStringWithPrefix( searchParams, "search_" ) );
		return PageUtil.toAjaxPageResult( listPage.getTotalElements(), listPage.getContent() );
	}

	/**
	 * 加载学年查看页面
	 * 
	 * @param model
	 * @param viewType
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/view/{viewType}")
	public String toView(Model model, @PathVariable String viewType, @RequestParam String id) {
		if (ViewType.Add.getView().equals( viewType )) {
			model.addAttribute( WebConstants.COMMAND, new Year() );
		} else {
			model.addAttribute( WebConstants.COMMAND, yearService.getOne( id ) );
		}
		model.addAttribute( "viewType", viewType );
		return "qso/year/form";
	}

	/**
	 * 保存提交的新增或修改资料
	 * 
	 * @param model
	 * @param command
	 * @param viewType
	 * @param result
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/save", method = { RequestMethod.POST })
	@ResponseBody
	public Object save(Model model, @ModelAttribute("command") @Valid Year command, @RequestParam String viewType, BindingResult result, HttpServletRequest req) {
		if (result.hasErrors()) {
			model.addAttribute( WebConstants.COMMAND, command );
			return toView( model, viewType, command.getId() );
		}

		Year enabledYear = yearService.findEnabled();
		if (null != enabledYear && "1".equals( command.getEnabled() )) {
			if (ViewType.Add.getView().equals( viewType ) || (!command.getId().equals( enabledYear.getId() ))) {
				return ajaxDoneError( "只有一个学期能够启用" );
			}
		}

		if (command.getDateF().compareTo( command.getDateT() ) > 0) {
			return ajaxDoneError( "结束时间不能早于开始时间" );
		}

		if (ViewType.Add.getView().equals( viewType )) {
			if (yearService.hasYearByTitle( command.getTitle() )) {
				return ajaxDoneError( this.getText( "save.yearSaveError" ) );
			}
			command.setDateCre( new Date() );
			command.setUserCre( getCurrentUserId() );
		} else {
			command.setDateUpd( new Date() );
			command.setUserUpd( getCurrentUserId() );
		}
		try {
			yearService.save( command );
			return ajaxDoneSuccess( this.getText( "save.success" ) );
		} catch (Exception e) {
			return ajaxDoneError( this.getText( "save.failed" ), e );
		}
	}

	/**
	 * 删除学年记录信息
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "/delete")
	@ResponseBody
	public Object delete(String ids) {
		boolean hasSusscesed = false;
		boolean hasErrored = false;

		for (String id : Arrays.asList( StringUtil.split( ids, "," ) )) {
			try {
				yearService.delete( id );
				hasSusscesed = true;
			} catch (Exception e) {
				hasErrored = true;
			}
		}

		if (hasSusscesed) {
			if (hasErrored) {
				return ajaxDoneError( "有些被引用的学期无法删除" );
			} else {
				return ajaxDoneSuccess( this.getText( "delete.success" ) );
			}
		} else {
			return ajaxDoneError( "该学期已经被引用，无法删除" );
		}
		// try {
		// yearService.deleteInBatch(Arrays.asList(StringUtils.split(ids, ",")));
		// return ajaxDoneSuccess(this.getText("delete.success"));
		// } catch (Exception e) {
		// return ajaxDoneError(this.getText("delete.failed"),e);
		// }
	}

	/**
	 * 唯一检查
	 * 
	 * @param id
	 * @param oldId
	 * @return
	 */
	@RequestMapping(value = "/checkUniqueId")
	@ResponseBody
	public boolean checkUniqueId(@RequestParam("id") String id, @RequestParam("oldId") String oldId) {
		if (id.equals( oldId )) {
			return true;
		}
		Year obj = yearService.getOne( id );
		return obj == null;
	}
}
